package proj.unions.resource;

import java.io.IOException;
import java.io.InputStream;

import org.json.JSONObject;

import proj.unions.general.GameView;
import proj.unions.general.L;
import proj.unions.general.OnMyCallBack;
import proj.unions.general.SuperTools;
import proj.unions.general.Text;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ResManager {
	
	public final static int  Res_Begin = 1000;
	public final static int  Res_End = 1001;
	public final static int  Res_EndToJump = 1002;
	
	//处理旧版本的资源
	public final static int  Res_DealOldRes = 2;
	//检测网络
	public final static int  Res_CheckNetwork = 3;
	//检测apk版本
	public final static int  Res_CheckAPKVersion = 4;
	//下载apk
	public final static int  Res_DownloadAPK = 5;
	//安装apk
	public final static int  Res_InstallAPK = 6;
	//检测资源
	public final static int  Res_CheckGameResVersion = 7;
	//下载lib
	public final static int  Res_DownloadGameLib = 8;
	//下载res
	public final static int  Res_DownloadGameRes = 9;
	//更新提示
	public final static int  Res_UpdateTips = 100;
	//刷新进度条
	public final static int  Res_UpdateProcess = 200;
	
	private Activity mActivity = null;
	private OnMyCallBack mOnMyCallBack = null;
	private boolean isbreakDraw = false;
	
	private RelativeLayout mRelativeLayout = null;
	private GameView mGameView = null;
	private TextView mCurTextView = null;
	private TextView mCurPercentTextView = null;
	
	private RelativeLayout mCurProgressBarLayout = null;
	private ProgressBar mCurProgressBar = null;
	private ImageView mCurImage = null;
	public static float mIamgeTotalength = 0; 
	public static float mCountPercent = 0;
	
	private Bitmap mLoadingbar = null;
	
	final static public boolean isSimpleMode = false;			//是否使用简单模式(true不增量,false增量)
	final static public boolean isUse_ZIP_Download = true;		//是否使用zip下载
	
	public ResManager(Activity a, RelativeLayout l)
	{
		mActivity = a;
		mRelativeLayout = l;
		isbreakDraw = false;
		mCountPercent = 0;
	}
	
	public boolean run(OnMyCallBack l)
	{
		if (l == null || mActivity == null)
			return false;
		mOnMyCallBack = l;
		init();
		mHandler.sendEmptyMessage(Res_Begin);
		return true;
	}
	
	private Handler mHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch(msg.what)
			{
				case Res_Begin://开始
				{
					mCountPercent = 0;
					L.d("=======Res_Begin========");
					if(!isSimpleMode)
						mHandler.sendEmptyMessage(Res_DealOldRes);
					else
						mHandler.sendEmptyMessage(Res_CheckGameResVersion);
//					mHandler.sendEmptyMessage(Res_End);
					break;
				}
				case Res_DealOldRes:
				{
					Message.obtain(mHandler, Res_UpdateTips, Text.getKey("Local_CheckPhoneEnvironment")/*"正在检测手机环境"*/).sendToTarget();
					mCountPercent = 0.02f;
					L.d("=======Res_DealOldRes========");
					new Thread(new DealOldRes(mActivity, new OnMyCallBack() {
						
						@Override
						public void onReceive(String arg0, int arg1, JSONObject json) {
							// TODO Auto-generated method stub
							mHandler.sendEmptyMessage(Res_CheckNetwork);
						}
					})).start();
					break;
				}
				case Res_CheckNetwork://检测网络
				{
					Message.obtain(mHandler, Res_UpdateTips, Text.getKey("Local_CheckPhoneNet")/*"正在检测手机网络"*/).sendToTarget();
					mCountPercent = 0.04f;
					L.d("=======Res_CheckNetwork========");
					new Thread(new CheckNetworkState(mActivity, new OnMyCallBack() {
						
						@Override
						public void onReceive(String arg0, int arg1, JSONObject json) {
							// TODO Auto-generated method stub
							if (arg1 == 1)
							{
								mHandler.sendEmptyMessage(Res_CheckAPKVersion);
							}
						}
					})).start();
					
					break;
				}
				case Res_CheckAPKVersion://检测apk版本
				{
					Message.obtain(mHandler, Res_UpdateTips, Text.getKey("Local_CheckApkVersion")/*"正在检测APK版本"*/).sendToTarget();
					mCountPercent = 0.06f;
					L.d("=======Res_CheckAPKVersion========");
					new Thread(new CheckAPKVersion(mActivity, new OnMyCallBack() {
					
						@Override
						public void onReceive(String arg0, int arg1, JSONObject json) {
							// TODO Auto-generated method stub
							if (arg1 == 1)
							{
								Message.obtain(mHandler, Res_DownloadAPK, json).sendToTarget();
							}
							else
							{
								mHandler.sendEmptyMessage(Res_CheckGameResVersion);
							}
						}
					})).start();
					break;
				}
				case Res_DownloadAPK://下载apk
				{
					Message.obtain(mHandler, Res_UpdateTips, Text.getKey("Local_DownloadNewApkVersion")/*"正在下载新APK版本"*/).sendToTarget();
					mCountPercent = 0.08f;
					L.d("=======Res_DownloadAPK========");
					new Thread(new DownloadAPK(mActivity, new OnMyCallBack() {
						
						@Override
						public void onReceive(String arg0, int arg1, JSONObject json) {
							// TODO Auto-generated method stub
							if(arg1 == 1)
							{
								Message.obtain(mHandler, Res_InstallAPK, json).sendToTarget();
							}
							else if(arg1 == 2)
							{
								Message.obtain(mHandler, Res_UpdateTips, arg0).sendToTarget();
							}
							else if(arg1 == -1)
							{
								mHandler.sendEmptyMessage(Res_End);
							}
						}
					}, (JSONObject)msg.obj)).start();
					break;
				}
				case Res_InstallAPK://安装apk
				{
					Message.obtain(mHandler, Res_UpdateTips, Text.getKey("Local_InstallNewApkVersion")/*"正在安装新APK版本"*/).sendToTarget();
					mCountPercent = 1.0f;
					L.d("=======Res_InstallAPK========");
					new Thread(new InstallAPK(mActivity, new OnMyCallBack() {
						
						@Override
						public void onReceive(String arg0, int arg1, JSONObject json) {
							// TODO Auto-generated method stub
							if(arg1 == 1)
							{
								mHandler.sendEmptyMessage(Res_End);
							}
						}
					}, (JSONObject)msg.obj)).start();
					break;
				}
				case Res_CheckGameResVersion://检测游戏资源
				{
					Message.obtain(mHandler, Res_UpdateTips, Text.getKey("Local_CheckRes")/*"正在检测资源"*/).sendToTarget();
					mCountPercent = 0.08f;
					L.d("=======Res_CheckGameResVersion========");
					new Thread(new CheckGameResVersion(mActivity, new OnMyCallBack() {
						
						@Override
						public void onReceive(String arg0, int arg1, JSONObject json) {
							// TODO Auto-generated method stub
							if(!isSimpleMode)
							{
								if(arg1 == 1)
								{
									Message.obtain(mHandler, Res_DownloadGameLib, json).sendToTarget();
								}
								else if(arg1 == -1)
									mHandler.sendEmptyMessage(Res_End);
							}
							else
								mHandler.sendEmptyMessage(Res_End);
						}
					}, (JSONObject)msg.obj)).start();
					break;
				}
				case Res_DownloadGameLib://下载游戏lib
				{
					L.d("=======Res_DownloadGameLib========");
					mCountPercent = 0.10f;
					new Thread(new DownloadGameLib(mActivity, new OnMyCallBack() {
						
						@Override
						public void onReceive(String arg0, int arg1, JSONObject json) {
							// TODO Auto-generated method stub
							if(arg1 == 1)
							{
								Message.obtain(mHandler, Res_DownloadGameRes, json).sendToTarget();
							}
							else if(arg1 == 2)
							{
								Message.obtain(mHandler, Res_UpdateTips, arg0).sendToTarget();
							}
						}
					}, (JSONObject)msg.obj)).start();
					break;
				}
				case Res_DownloadGameRes://下载游戏资源
				{
					L.d("=======Res_DownloadGameRes========");
					mCountPercent = 0.25f;
					new Thread(new DownloadGameRes(mActivity, new OnMyCallBack() {
						
						@Override
						public void onReceive(String arg0, int arg1, JSONObject json) {
							// TODO Auto-generated method stub
							if(arg1 == 1)
							{
								mHandler.sendEmptyMessage(Res_End);
							}
							else if(arg1 == 2)
							{
								Message.obtain(mHandler, Res_UpdateTips, arg0).sendToTarget();
							}
						}
					}, (JSONObject)msg.obj)).start();
					break;
				}
				case Res_UpdateTips://更新tips
				{
					String ret = (String)msg.obj;
					mCurTextView.setText(ret);
					byte byteLen[] = ret.getBytes();
					int len = byteLen.length;
					int size = (1280 / 2) - (int)(len * 5);
					mCurTextView.setX(_tw(size));
					mCurPercentTextView.setText(String.valueOf((int)Math.floor(mCountPercent * 100)) + "%");
					
					try {
						setPercent(mCountPercent);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						L.d("===setPercent IOException e ");
					}
					
					break;
				}
				case Res_UpdateProcess:
				{
					try {
						setPercent(mCountPercent);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						L.d("===setPercent IOException e ");
					}
					break;
				}
				case Res_End://结束
				{
					L.d("=======Res_End========");
					mCountPercent = 1.0f;
					isbreakDraw = true;
					Message.obtain(mHandler, Res_UpdateTips, Text.getKey("Local_LoadRes")/*"准备加载资源"*/).sendToTarget();
					
					new Thread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							try {
								Thread.sleep(500);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

							Message.obtain(mHandler, Res_EndToJump).sendToTarget();
						}
					}).start();
					
					break;
				}
				case Res_EndToJump:
				{
					mOnMyCallBack.onReceive("", -1, null);
					break;
				}
			}
		};
	};
	
	private void init()
	{
		int width = 1280;
		int height = 720;
		
		mCurTextView = new TextView(mActivity);
		mCurTextView.setTextSize(18);
		mCurTextView.setTextColor(Color.WHITE);
		mCurTextView.setText("");
		mRelativeLayout.addView(mCurTextView, _tw(width), _th(height - height/10));
		mCurTextView.setX(_tw(width / 7 * 3 - 56));
		mCurTextView.setY(_th(600 + 30));
		
		mCurProgressBarLayout = new RelativeLayout(mActivity);
		mRelativeLayout.addView(mCurProgressBarLayout, _tw(width / 5 * 3), _th(20));
		mCurProgressBarLayout.setX(_tw(width / 5));
		mCurProgressBarLayout.setY(_th(600));
		
		InputStream is = null;
		try {
			mCurPercentTextView = new TextView(mActivity);
			mCurPercentTextView.setTextSize(15);
			mCurPercentTextView.setTextColor(Color.WHITE);
			mCurPercentTextView.setText("");
			mRelativeLayout.addView(mCurPercentTextView, _tw(width), _th(height - height/10));
			mCurPercentTextView.setX(_tw(width / 2 - 24));
			mCurPercentTextView.setY(_th(600 - 32));
			
			
			mCurProgressBar = new ProgressBar(mActivity);
			
			is = mActivity.getAssets().open("loadingBarBg.png");
			Bitmap loadingBarBg = GameView.getNewBitmap(BitmapFactory.decodeStream(is));
			mCurProgressBar.setBackground(new BitmapDrawable(loadingBarBg));
			

			mCurProgressBar.setIndeterminateDrawable(null);
			mCurProgressBarLayout.addView(mCurProgressBar, _tw(width / 5 * 3), _th(20));

			mIamgeTotalength = _tw(width / 5 * 3 - 14);
			is = mActivity.getAssets().open("loadingBar.png");
			mLoadingbar = GameView.getNewBitmap(BitmapFactory.decodeStream(is));

			mCurImage = new ImageView(mActivity);
			mCurImage.setBackground((new BitmapDrawable(mLoadingbar)));
			
			setPercent(0.0f);
//			mHandler.obtainMessage(Res_UpdateProcess).sendToTarget();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	public void setPercent(float arg0) throws IOException
	{
		if(mCurProgressBarLayout != null)
		{	
			int ret = (int)(arg0 * mIamgeTotalength);
			mCurProgressBarLayout.removeView(mCurImage);
			mCurProgressBarLayout.addView(mCurImage, ret, _th(20 - 8));
			mCurImage.setX(_tw(7));
			mCurImage.setY(_th(4));
		}
	}
	
	public int _tw(int origina_lw)
	{
		return SuperTools.getInstance()._tw(origina_lw);
	}
	public int _th(int origina_lh)
	{
		return SuperTools.getInstance()._th(origina_lh);
	}
	
}
